//@ sourceURL= Micoua_OCRTranslate.js
(function () {
    /** 常量 */
    var languagesCorrespon = {
        "语言名称": ["语言名称", "识别语言", "翻译语言"],
        "自动检测": ["自动检测", "auto", "auto"],
        "中文": ["中文", "chi_sim", "zh"],
        "英语": ["英语", "eng", "en"],
        "法语": ["法语", "fra", "fra"],
        "日语": ["日语", "jpn", "jp"],
        "韩语": ["韩语", "", "kor"],
        "德语": ["德语", "deu", "de"],
        "俄语": ["俄语", "rus", "ru"],
        "粤语": ["粤语", "", "yue"],
        "泰语": ["泰语", "tha", "th"],
        "文言文": ["文言文", "", "wyw"],
        "希腊语": ["希腊语", "ell", "el"],
        "荷兰语": ["荷兰语", "nld", "nl"],
        "波兰语": ["波兰语", "pol", "pl"],
        "丹麦语": ["丹麦语", "dan", "dan"],
        "芬兰语": ["芬兰语", "fin", "fin"],
        "捷克语": ["捷克语", "ces", "cs"],
        "瑞典语": ["瑞典语", "swe", "swe"],
        "越南语": ["越南语", "vie", "vie"],
        "繁体中文": ["繁体中文", "chi_tra", "cht"],
        "意大利语": ["意大利语", "ita", "it"],
        "西班牙语": ["西班牙语", "spa", "spa"],
        "葡萄牙语": ["葡萄牙语", "por", "pt"],
        "阿拉伯语": ["阿拉伯语", "ara", "ara"],
        "匈牙利语": ["匈牙利语", "hun", "hu"],
        "保加利亚语": ["保加利亚语", "bul", "bul"],
        "爱沙尼亚语": ["爱沙尼亚语", "est", "est"],
        "罗马尼亚语": ["罗马尼亚语", "ron", "rom"],
        "斯洛文尼亚语": ["斯洛文尼亚语", "slv", "slo"]
    };

    /** 全局变量 */
    var isIntimeTranslate = false;
    var baiduTranslateURL = "https://api.fanyi.baidu.com/api/trans/vip/translate"; // 百度翻译URL
    var baiduCharCountPageURL = "https://api.fanyi.baidu.com/api/trans/product/desktop"; // 百度翻译管理页面URL
    var baiduCharCountDataURL = "https://api.fanyi.baidu.com/api/trans/product/desktopint?req=query_balance"; // 百度翻译字符数据获取URL
    var baseData = {"(源语言-目标语言)数据内容": ["数据类型", "源语言", "目标语言", "处理结果"]}; // 数据模板
    var editData = {}; // 编辑区数据
    var identifyData = {}; // 识别区数据
    var identifyDataCache = {}; // 识别区数据缓存
    var translateDataCache = {}; // 翻译区数据缓存
    var identifyViewDataNum = 0; // 识别区展示数据编号
    var identifyViewData = {"展示编号": "识别结果"}; // 识别区展示数据
    var translateViewDataNum = 0; // 翻译区展示数据编号
    var translateViewData = {"展示编号": "翻译结果"}; // 翻译区展示数据
    var identifyLang = languagesCorrespon["自动检测"]; // 默认识别区语言对象
    var translateLang = languagesCorrespon["中文"]; // 默认翻译区语言对象
    var editDefultContent = "可直接粘贴图片进行内容识别并翻译"; // 编辑框默认文案
    var identifyDefultContent = "仅支持Ctrl+Shift+V粘贴纯文本"; // 识别框默认文案
    var translateDefultContent = "在编辑区输入内容即可翻译"; // 翻译框默认文案
    var maxCharLength = 102400; // 单词最大处理数据长度
    var hiddenPromptBoxTag = true; // 自动隐藏提示框标记

    /** 基础入口 */
    function main() {
        listen();
        updateCacheList();
        baiduCharData(true);
    }

    /** 更新缓存列表 */
    function updateCacheList() {
        $("#identifyCachetUl").html(getCacheHtml(identifyDataCache));
        $("#translateCachetUl").html(getCacheHtml(translateDataCache));

        function getCacheHtml(dataObj) {
            if (!dataObj) { return "<font class='micouaColor3'>当前没有任何缓存</font>"; }
            var cacheHtml = "";
            for (var objKey in dataObj) {
                if (!dataObj[objKey]) { continue; }
                var currentDataObj = dataObj[objKey];
                var objKeyHtml = objKey.substring(objKey.indexOf(")") + 1, objKey.length);
                cacheHtml += "<li><font class='micouaColor'>\"" + (objKeyHtml.length > 15 ? objKeyHtml.substr(0, 15) + "..." : objKeyHtml) + "\"</font>: [";
                cacheHtml += "<font class='micouaColor2'>\"" + currentDataObj[0] + "\"</font>,";
                cacheHtml += "<font class='micouaColor2'>\"" + currentDataObj[1] + "\"</font>,";
                cacheHtml += "<font class='micouaColor2'>\"" + currentDataObj[2] + "\"</font>,";
                cacheHtml += "<font class='micouaColor2'>\"" + currentDataObj[3] + "\"</font>]&nbsp;&nbsp;</li>";
            }
            if (cacheHtml) {
                $("#clearIdentifyCache").html("识别区缓存[" + (Object.keys(identifyDataCache).length) + "]");
                $("#identifyCacheP").html("缓存列表[" + (Object.keys(identifyDataCache).length) + "] ▼");
                $("#clearTranslateCache").html("翻译区缓存[" + (Object.keys(translateDataCache).length) + "]");
                $("#translateCacheP").html("缓存列表[" + (Object.keys(translateDataCache).length) + "] ▼");
            } else { cacheHtml = "<font class='micouaColor3'>当前没有任何缓存</font>"; }
            return cacheHtml;
        }
    }

    /** 获取百度字符统计数据
     *  @param isPageFirst 页面刷新标记
     */
    function baiduCharData(isPageFirst) {
        $.ajax({
            url: baiduCharCountDataURL, type: "get", dataType: "jsonp", success: function (charDataResult) {
                var promptBox = $("#promptBox");
                var promptBoxHtml = "";
                var isAutoHidden = true;
                if (!isPageFirst && charDataResult.error_code == "68000") {
                    var loginBaiduHtml = "<a id='loginBaidu' href='#' style='text-decoration: none;'>登录百度</a>";
                    promptBoxHtml = "字符统计功能需要" + loginBaiduHtml + "后方能使用";
                    isAutoHidden = false;
                    hiddenPromptBoxTag = false;
                }
                if (charDataResult.error_code == "52000") {
                    var charData = charDataResult.data.flow;
                    var curMonthWordCount = charData.CurMonthWordCount;
                    if (curMonthWordCount > 1500000) {
                        promptBoxHtml = "更新成功，当月字符使用量为" + numComma(curMonthWordCount) + "，本月将暂停使用翻译服务，次月恢复使用";
                        return;
                    } else if (curMonthWordCount > 1200000) { promptBoxHtml = "更新成功，当月字符使用量为" + numComma(curMonthWordCount) + "，请注意可用字符余量"; } else { promptBoxHtml = "更新成功，当月字符使用量为" + numComma(curMonthWordCount); }

                    $("#yesterdayWordCount").html(numComma(charData.YesterdayWordCount));
                    $("#yesterdayDate").html(charData.YesterdayDate);
                    $("#yesterdayCost").html(numComma(charData.YesterdayCost) + "&nbsp;&nbsp;");
                    $("#curMonthWordCount").html(numComma(charData.CurMonthWordCount));
                    $("#curMonth").html(charData.CurMonth);
                    $("#curMonthCost").html(numComma(charData.CurMonthCost) + "&nbsp;&nbsp;");
                    $("#totalWordCount").html(numComma(charData.TotalWordCount));
                    $("#totalCost").html(numComma(charData.TotalCost));
                }

                if (!isPageFirst) {
                    showPrompBox(promptBoxHtml, isAutoHidden, 5);
                    $("#loginBaidu").click(function () { window.open("https://www.baidu.com"); });
                }
            }
        });
    }

    /** 数字加逗号处理
     *  @param num 待处理数字
     */
    function numComma(num) { return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); }

    /** 展示提示框
     *  @param showHtml 需要展示的文案
     *  @param isAutoHidden 自动隐藏标签
     *  @param showTime 文案展示的时间, 以秒为单位
     */
    function showPrompBox(showHtml, isAutoHidden, showTime) {
        var promptBox = $("#promptBox");
        if (promptBox.css("opacity") != "0") { return; }
        promptBox.html(showHtml);
        promptBox.css({visibility: "visible", opacity: 1, transition: "all 0.5s"});
        if (isAutoHidden) {
            if (!showTime) { showTime = 3 * 1000; }
            setTimeout(function () {
                promptBox.css({
                    visibility: "hidden",
                    opacity: 0,
                    transition: "all 0.5s"
                });
            }, showTime * 1000);
            promptBox.css({background: "rgba(200, 255, 190)"});
        } else {
            promptBox.css({background: "rgba(255, 196, 196, 1)"});
        }
    }

    /** 获取对象key值中正确的数据内容
     *  @param dataKey 对象的key值
     */
    function getDataKey(dataKey) { return dataKey.substring(dataKey.indexOf(")"), dataKey.length); }

    /** 根据数据内容得到完整的对象key值
     *  @param dataContent 数据内容
     *  @param fromLang 源语言对象
     *  @param toLang 目标语言对象
     */
    function setDataKey(dataContent, fromLang, toLang) { return "(" + (fromLang ? fromLang[0] + "-" : "") + toLang[0] + ")" + dataContent; }

    /** 获取编辑框内容 */
    function getEditContent() {
        if ($("#editContent").html().length > maxCharLength) {
            showPrompBox("每次最多" + maxCharLength + "个字符，请删减或分批次处理", true, 5);
            return;
        }
        editData = {};
        identifyViewData = {};
        identifyViewDataNum = 0;
        var contentType = "";
        var currentEditData;
        var editHtmlNoBr = $("#editContent").html().replace(/&nbsp;/g, "").replace(/<br>/g, "");
        if (!editHtmlNoBr) {
            showPrompBox("当前无法获取可粘贴内容", true, 5);
            return;
        }
        while (editHtmlNoBr) {
            editHtmlNoBr = StringUtils.trim(editHtmlNoBr);
            if (StringUtils.startsWith(editHtmlNoBr, "<img")) {
                editHtmlNoBr = editHtmlNoBr.replace(/<img.*?src=\"/, "").replace(/\".*?>/, "");
                contentType = "img";
                continue;
            } else if (StringUtils.startsWith(editHtmlNoBr, "<")) {
                editHtmlNoBr = editHtmlNoBr.replace(/<.*?>/, "").replace(/<\/.*?>/, "");
                continue;
            } else {
                contentType = contentType == "img" ? "img" : "text";
                currentEditData = editHtmlNoBr.indexOf("<") == -1 ? editHtmlNoBr : editHtmlNoBr.substring(0, editHtmlNoBr.indexOf("<"));
                editHtmlNoBr = editHtmlNoBr.replace(currentEditData, "");
            }
            currentEditData = StringUtils.trim(currentEditData);
            identifyViewData[identifyViewDataNum++] = currentEditData;
            identifyLang = identifyLang[0] != "自动检测" ? identifyLang : languagesCorrespon["英语"];
            editData[currentEditData] = [contentType != "" ? contentType : "undefined", "", identifyLang[0], currentEditData];
            var editLangKey = setDataKey(currentEditData, "", identifyLang);
            identifyData[editLangKey] = editData[currentEditData];
            if (identifyDataCache[editLangKey] == undefined) { identifyDataCache[editLangKey] = ["", "", "", ""]; }
        }
        identifyContent();
    }

    /** 识别内容 */
    function identifyContent() {
        // 遍历编辑区数据判断是否需要识别
        var isIdentify = false;
        var isLast = false;
        var identifyTimes = 0;
        for (var editKey in editData) {
            isLast = Object.keys(editData)[Object.keys(editData).length - 1] == editKey;
            var identifyLangKey = setDataKey(editKey, "", identifyLang);
            var identifyType = editData[editKey][0];
            var currentIdentifyCache = identifyDataCache[identifyLangKey];
            var matchIdentifyCache = currentIdentifyCache != undefined && currentIdentifyCache[0] == identifyType && currentIdentifyCache[2] == identifyLang[0];
            if (matchIdentifyCache) { continue; }
            if (identifyType == "img") {
                tesseractIdentify(editKey, isLast);
                if (!isIdentify) { console.log("☆====================识别====================☆"); }
                isLast = isLast ? false : true;
                isIdentify = true;
            } else if (identifyType == "text") {
                identifyData[identifyLangKey][3] = editKey;
                identifyDataCache[identifyLangKey] = identifyData[identifyLangKey];
                $("#clearIdentifyCache").html("识别区缓存[" + (Object.keys(identifyDataCache).length) + "]");
                $("#identifyCacheP").html("缓存列表[" + (Object.keys(identifyDataCache).length) + "] ▼");
                updateCacheList();
            }
        }
        if (!isIdentify || isLast) {
            loadIdentifyViewData();
            getIdentityContent();
        }

        function tesseractIdentify(identifyStr, canTranslate) {
            $("#identifing").html("识别中(" + identifyTimes++ + ")");
            var identfifyLangKey = setDataKey(identifyStr, "", identifyLang);
            Tesseract.recognize(identifyStr, {
                lang: identifyLang[1]
            }).progress(function (progressResult) {
                $("#identifing").html("识别中(" + identifyTimes++ + ")");
            }).then(function (identifyResult) {
                var identifyResultContent = identifyData[identfifyLangKey][3] = identifyResult.text.replace(/[\r\n]/g, "");
                identifyDataCache[identfifyLangKey] = identifyData[identfifyLangKey];
                $("#identifing").html("待识别");
                $("#clearIdentifyCache").html("识别区缓存[" + (Object.keys(identifyDataCache).length) + "]");
                $("#identifyCacheP").html("缓存列表[" + (Object.keys(identifyDataCache).length) + "] ▼");
                updateCacheList();
                loadIdentifyViewData();
                if (canTranslate) { getIdentityContent(); }
            });
        }
    }

    /** 加载识别结果展示数据 */
    function loadIdentifyViewData() {
        if (Object.keys(identifyViewData).length == 0) {
            $("#identifyContent").html("<font style='color: red'>无法获取识别结果</font>");
            return;
        }
        var identifyViewHtml = "";
        for (var identifyViewKey in identifyViewData) {
            if (identifyViewKey == "展示编号") { continue; }
            var currentIdentifyData = identifyDataCache[setDataKey(identifyViewData[identifyViewKey], "", identifyLang)];
            if (!currentIdentifyData || !currentIdentifyData[0]) { return; }
            identifyViewHtml = identifyViewHtml + "<div>" + identifyDataCache[setDataKey(identifyViewData[identifyViewKey], "", identifyLang)][3] + "</div>";
        }
        $("#identifyContent").html(identifyViewHtml.toLowerCase());
        $("#identifyContent").css({color: "rgba(0, 0, 0, 1)"});
    }

    /** 获取识别框内容 */
    function getIdentityContent() {
        if ($("#identifyContent").html().length > maxCharLength) {
            showPrompBox("每次最多" + maxCharLength + "个字符，请删减或分批次处理", true, 5);
            return;
        }
        identifyData = {};
        translateViewData = {};
        translateViewDataNum = 0;
        var currentIdentifyData;
        var identifyHtmlNoBr = $("#identifyContent").html().replace(/&nbsp;/g, "").replace(/<br>/g, "").replace(/<div><\/div>/g, "");
        while (identifyHtmlNoBr) {
            if (identifyHtmlNoBr.indexOf("<div") == 0) {
                // div开头
                currentIdentifyData = identifyHtmlNoBr.substring(5, identifyHtmlNoBr.indexOf("</div>"));
                identifyHtmlNoBr = identifyHtmlNoBr.replace(/<div>.*?<\/div>/, "");
            } else {
                // 文本开头
                currentIdentifyData = identifyHtmlNoBr.indexOf("<") == -1 ? identifyHtmlNoBr : identifyHtmlNoBr.substring(0, identifyHtmlNoBr.indexOf("<"));
                identifyHtmlNoBr = identifyHtmlNoBr.replace(currentIdentifyData, "");
            }
            currentIdentifyData = StringUtils.trim(currentIdentifyData);
            translateViewData[translateViewDataNum++] = currentIdentifyData;
            var identifyLangKey = setDataKey(currentIdentifyData, "", identifyLang);
            identifyDataCache[identifyLangKey] = identifyData[identifyLangKey] = ["text", "", identifyLang[0], currentIdentifyData];
            $("#clearIdentifyCache").html("识别区缓存[" + (Object.keys(identifyDataCache).length) + "]");
            $("#identifyCacheP").html("缓存列表[" + (Object.keys(identifyDataCache).length) + "] ▼");
            updateCacheList();
        }
        translateContent();
    }

    /** 翻译内容 */
    function translateContent() {
        if (!$("#identifyContent").html()) {
            $("#translateContent").html("<font style='color: red'>请输入需翻译内容</font>");
            return;
        }

        // 遍历识别区数据判断是否需要翻译
        var isTranslate = false;
        for (var identifyKey in identifyData) {
            var translateStr = identifyData[identifyKey][3];
            var currentTranslateCache = translateDataCache[setDataKey(translateStr, identifyLang, translateLang)];
            var currentTranslateLangStr = currentTranslateCache != undefined && currentTranslateCache[1].indexOf("自动检测") == -1 ? currentTranslateCache[1] : "自动检测";
            var matchTranslateCache = currentTranslateCache != undefined && currentTranslateLangStr == identifyLang[0] && currentTranslateCache[2] == translateLang[0];
            if (matchTranslateCache) { continue; }
            baiduTranslate(identifyData[identifyKey][0], translateStr);
            if (!isTranslate) { console.log("★====================翻译====================★"); }
            isTranslate = true;
        }
        if (!isTranslate) { loadTranslateViewData(); }

        function baiduTranslate(identifyType, translateStr) {
            // 请求翻译api参数
            var appid = "";
            var key = "";
            var salt = new Date().getTime();
            var sign = MD5(appid + translateStr + salt + key);
            $.ajax({
                url: baiduTranslateURL,
                type: "get",
                dataType: "jsonp",
                data: {
                    q: translateStr,
                    appid: appid,
                    salt: salt,
                    from: identifyLang[2],
                    to: translateLang[2],
                    sign: sign
                },
                success: function (translateResult) {
                    var translateLangStr = identifyLang[0];
                    if (translateLangStr == "自动检测") {
                        for (var langKey in languagesCorrespon) {
                            if (languagesCorrespon[langKey][2] == translateResult.from) {
                                translateLangStr = "自动检测(" + languagesCorrespon[langKey][0] + ")";
                                break;
                            }
                        }
                    }
                    var translateLangKey = setDataKey(translateStr, identifyLang, translateLang);
                    translateDataCache[translateLangKey] = [identifyType, translateLangStr, translateLang[0], translateResult.trans_result[0].dst];
                    $("#clearTranslateCache").html("翻译区缓存[" + (Object.keys(translateDataCache).length) + "]");
                    $("#translateCacheP").html("缓存列表[" + (Object.keys(translateDataCache).length) + "] ▼");
                    updateCacheList();
                    loadTranslateViewData();
                }
            });
        }
    }

    /** 加载翻译结果展示数据 */
    function loadTranslateViewData() {
        if (Object.keys(translateViewData).length == 0) {
            $("#translateContent").html("<font style='color: red'>无法获取翻译结果</font>");
            return;
        }
        var translateViewHtml = "";
        for (var translateViewKey in translateViewData) {
            if (translateViewKey == "展示编号") { continue; }
            var currentTranslateData = translateDataCache[setDataKey(translateViewData[translateViewKey], identifyLang, translateLang)];
            if (!currentTranslateData || !currentTranslateData[0]) { return; }
            translateViewHtml = translateViewHtml + translateDataCache[setDataKey(translateViewData[translateViewKey], identifyLang, translateLang)][3] + "<br>";
        }
        $("#translateContent").html(translateViewHtml.toLowerCase());
        $("#translateContent").css({color: "rgba(0, 0, 0, 1)"});

        console.log("★模板★【" + getConsoleStr(baseData) + "】");
        console.log("♣♣♣识别缓存♣♣♣【" + getConsoleStr(identifyDataCache) + "】");
        console.log("♦♦♦翻译缓存♦♦♦【" + getConsoleStr(translateDataCache) + "】");
    }

    /** 拼接打印结果数据
     *  @param dataObj 数据对象
     */
    function getConsoleStr(dataObj) {
        var consoleStr = "{";
        var consoleSpace = "                ";
        for (var objKey in dataObj) {
            var currentDataObj = dataObj[objKey];
            consoleStr += "\"" + (objKey.length > 50 ? objKey.substr(0, 50) + "..." : objKey) + "\":[";
            consoleStr += "\"" + currentDataObj[0] + "\",\"" + currentDataObj[1] + "\",\"" + currentDataObj[2] + "\",";
            consoleStr += "\"" + (currentDataObj[3].length > 50 ? currentDataObj[3].substr(0, 50) + "..." : currentDataObj[3]) + "\"],\n" + consoleSpace;
        }
        consoleStr = consoleStr.length < 2 ? "{}" : consoleStr.substring(0, consoleStr.length - consoleSpace.length - 2) + "}";
        return consoleStr;
    }

    /** 监听事件 */
    function listen() {
        /* 监听提示框 */
        $("#promptBox").click(function () { hiddenPromptBoxTag = true; });
        $("#promptBox").mouseout(function () {
            if (hiddenPromptBoxTag && $(this).css("opacity") != "0") {
                $(this).css({
                    visibility: "hidden",
                    opacity: 0,
                    transition: "all 0.5s"
                });
            }
        });

        /* 监听内容框焦点事件 */
        listenContentChange($("#editContent"), editDefultContent);
        listenContentChange($("#identifyContent"), identifyDefultContent);

        /* 候选列表 */
        $("#identifyLanguageText li, #translateLanguageText li, #translateTypeDiv li").click(function () { $(".titleListUl").css("display", "none"); });
        $(".titleButtonDiv").mouseout(function () { $(this).find("ul").css("display", "none"); });
        $(".titleButtonDiv").mouseover(function () { $(this).find("ul").css("display", "block"); });

        /* 字符统计 */
        $("#baiduCharacterCountA").click(function () { window.open(baiduCharCountPageURL); });
        $("#reloadCharCount").click(function () {
            $("#promptBox").css({visibility: "hidden", opacity: 0});
            baiduCharData(false);
        });

        /* 识别区-翻译区滚动条关联 */
        $("#identifyContent").scroll(function () { if ($("#translateContent").css("opacity") == 0.9) { $("#translateContent").scrollTop($(this).scrollTop()); } });
        $("#translateContent").scroll(function () { if ($("#identifyContent").css("opacity") == 0.9) { $("#identifyContent").scrollTop($(this).scrollTop()); } });

        /* 监听清空按钮点击事件 */
        $("#clearEditContent, #clearAll, #clearAllContent").click(function () {
            editData = {};
            $("#editContent").html(editDefultContent);
            $("#editContent").css({color: "rgba(128, 128, 128, 1)"});
            showPrompBox("清空成功", true, 3);
        });
        $("#clearIdentifyContent, #clearAll, #clearAllContent").click(function () {
            identifyData = {};
            $("#identifyContent").html(identifyDefultContent);
            $("#identifyContent").css({color: "rgba(128, 128, 128, 1)"});
            showPrompBox("清空成功", true, 3);
        });
        $("#clearTranslateContent, #clearAll, #clearAllContent").click(function () {
            $("#translateContent").html(translateDefultContent);
            $("#translateContent").css({color: "rgba(128, 128, 128, 1)"});
            showPrompBox("清空成功", true, 3);
        });
        $("#clearIdentifyCache, #clearAll, #clearAllCache").click(function () {
            identifyDataCache = {};
            updateCacheList();
            $("#clearIdentifyCache").html("识别区缓存");
            $("#identifyCacheP").html("缓存列表 ▼");
            showPrompBox("清空成功", true, 3);
        });
        $("#clearTranslateCache, #clearAll, #clearAllCache").click(function () {
            translateDataCache = {};
            updateCacheList();
            $("#clearTranslateCache").html("翻译区缓存");
            $("#translateCacheP").html("缓存列表 ▼");
            showPrompBox("清空成功", true, 3);
        });

        /* 监听识别翻译按钮 */
        $("#runIdentify").click(function () { getEditContent(); });
        $("#runTranslate").click(function () { getIdentityContent(); });

        /* 监听识别快捷键 Alt+R */
        $("#editContent, #identifyContent").focus(function () {
            $(this).keyup(function () {
                if ($(this).html() && event.altKey && event.keyCode == 82) { getEditContent(); }
            });
        });
        /* 监听翻译快捷键 Alt+G */
        $("#editContent, #identifyContent").focus(function () {
            $(this).keyup(function () {
                if ($(this).html() && event.altKey && event.keyCode == 71) { getIdentityContent(); }
            });
        });

        /* 监听编辑框变更事件 */
        $("#editContent").keyup(function (event) {
            var keyCode = event.keyCode;
            if ((isIntimeTranslate && (keyCode == 13 || keyCode == 32)) || (event.ctrlKey && keyCode == 86) || (event.ctrlKey && event.shiftKey && keyCode == 86)) {
                identifyLang = languagesCorrespon[$("#identifyLangP").text().replace(" ▼", "")];
                translateLang = languagesCorrespon[$("#translateLangP").text().replace(" ▼", "")];
                getEditContent();
            }
        });

        /* 监听识别框变更事件 */
        $("#identifyContent").keyup(function (event) {
            var keyCode = event.keyCode;
            if (event.ctrlKey && !event.shiftKey && keyCode == 86) {
                $("#identifyContent").html("<font class='micouaColor3'>" + identifyDefultContent + "</font>");
                $("#identifyContent").blur();
            }
            if ((isIntimeTranslate && (keyCode == 13 || keyCode == 32)) || (event.ctrlKey && event.shiftKey && keyCode == 86)) {
                identifyLang = languagesCorrespon[$("#identifyLangP").text().replace(" ▼", "")];
                translateLang = languagesCorrespon[$("#translateLangP").text().replace(" ▼", "")];
                getIdentityContent();
            }
        });

        /* 监听选项选择事件 */
        $(".titleListUl li").click(function () {
            if ($("#identifing").text().indexOf("识别中") != -1) {
                var promptBox = $("#promptBox");
                if (promptBox.css("opacity") != "0") { return; }
                promptBox.html("识别图片中，请稍后...");
                promptBox.css({visibility: "visible", opacity: 1});
                return;
            }
            editData = {};
            identifyData = {};
            var langText = this.innerHTML;
            // 判断修改语言来源
            if (this.value == 1) {
                $("#identifyLangP").html(langText + " ▼");
                identifyLang = languagesCorrespon[langText];
                getEditContent();
            } else if (this.value == 2) {
                $("#translateLangP").html(langText + " ▼");
                translateLang = languagesCorrespon[langText];
                getIdentityContent();
            }
        });
        $("#translateTypeDiv li").click(function () {
            if (this.innerHTML.indexOf("即时翻译") != -1) {
                isIntimeTranslate = true;
                $("#translateTypeP").html("即时翻译 ▼");
            }
            if (this.innerHTML.indexOf("手动翻译") != -1) {
                isIntimeTranslate = false;
                $("#translateTypeP").html("手动翻译 ▼");
            }
        });

        /* 监听编辑区粘贴图片事件 */
        document.querySelector("#editContent").addEventListener("paste", function (event) {
            var cbd = event.clipboardData;
            var ua = window.navigator.userAgent;
            for (var i = 0; i < cbd.items.length; i++) {
                var item = cbd.items[i];
                if (item.kind == "file") {
                    var blob = item.getAsFile();
                    if (blob.size === 0) { return; }
                    var reader = new FileReader();
                    var imgs = new Image();
                    imgs.file = blob;
                    reader.onload = (function (aImg) { return function (e) { aImg.src = e.target.result; }; })(imgs);
                    reader.readAsDataURL(blob);
                    this.appendChild(imgs);
                }
            }
            setFocus(this);
        }, false);

        /** 内容框聚离焦文案展示
         *  @param jQObj jQuery对象
         *  @param viewText 展示文案
         */
        function listenContentChange(jQObj, viewText) {
            jQObj.focus(function () {
                jQObj.css({color: "rgba(0, 0, 0, 1)"});
                if (jQObj.text() == viewText) { jQObj.html(""); }
            });
            jQObj.blur(function () {
                if (!jQObj.html()) { jQObj.html(viewText); }
                if (jQObj.text() == viewText) { jQObj.css({color: "rgba(128, 128, 128, 1)"}); }
            });
        }

        /** 定位光标到末尾
         *  @param DOMObj DOM对象
         */
        function setFocus(DOMObj) {
            DOMObj.focus();
            var range = document.createRange();
            range.selectNodeContents(DOMObj);
            range.collapse(false);
            var sel = window.getSelection();

            // 判断光标位置，如不需要可删除
            if (sel.anchorOffset != 0) { return; }
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }

    /** 加载完所有数据后进入主函数 */
    if (true) main();
})();